<?php
class stContestUser_model extends stmodel_2_1{

    public function __construct($config) {
        parent::__construct ( $config );
        $this->setTableName("st_contest_user");
        $this->setPrimaryKey('user_id');
    }

    public function updateRecords($data = '', $where = ''){
        if(count($data)>0){
            foreach ($data as $value) {                
                $where = array($this->_primaryKey => $value[$this->_primaryKey]);
                $this->update($this->_tableName, $value, $where);
            }
        }
        return false;
    }    

    public function countRecords($args = ''){                
        $result = $this->getRecords($args);        
        return count($result);
        
    }
    
    public function deleteRecords($id = ''){
        $query = "DELETE FROM $this->_tableName
        WHERE `{$this->_primaryKey}` = $id";
        
        $sql = "select *, count(*) as totaldup from st_contest_user_like_data where user_id = {$id} group by data_id";
        $datas = $this->get_results($sql);
        
        $this->query($query);
        
        // update all contests were liked by this user                
//        print_r($datas);die;
        foreach($datas as $data) {
            $this->updateLike($data->data_id);
        }
        
        return true;
    }   
    
    public function updateLike($dataID) {
        $sql = "update st_contest_data set total_like = (select count(*) as total from st_contest_user_like_data where data_id = {$dataID} group by data_id) where data_id = {$dataID}";
        $this->query($sql);
    }
}